﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace Wilke.Interactive.Drone.PlayGround
{
    public class Utilities
    {
        public static string GenerateNewNumberedFileName(string path, string fileNamePattern, string extension)
        {
            List<int> usedIndexes = new List<int>();

            Regex regex = new Regex(fileNamePattern + "[0-9*]*." + extension, RegexOptions.Compiled);

            List<string> fileNames = Directory.GetFiles(path, fileNamePattern + "*." + extension).ToList<String>();

            foreach (var fileName in fileNames)
            {
                Match match = regex.Match(fileName);

                if (match.Captures.Count > 0)
                {
                    string indexValue = match.Captures[0].Value.Replace(fileNamePattern, "").Replace("." + extension, "");

                    usedIndexes.Add(Int32.Parse(indexValue));
                }
            }

            int currentIndex = 0;

            while (true)
            {
                if (!usedIndexes.Contains(++currentIndex))
                {
                    break;
                }
            }

            return String.Format("{0}{1}.{2}", fileNamePattern, currentIndex, extension);
        }
    }
}
